package com.way2sms.way2inbox;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.provider.Telephony;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import www.way2inbox.adapter.ContactsAdapter;
import www.way2inbox.common.PrintMsg;
import www.way2inbox.data.phonecontacts_model;
import www.way2inbox.settings.DeviceDetailsClass;

public class Contacts extends ActionBarActivity implements  OnItemClickListener {
    List<phonecontacts_model> planetsList = new ArrayList<phonecontacts_model>();
    ContactsAdapter aAdpt;
    Cursor contacts;
    ListView contactslist;
    EditText search;
    RelativeLayout Chat_Send,back;
    String number;
    String myPackageName;
    DeviceDetailsClass detailsclass;
    RelativeLayout default_application;
    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);setContentView(R.layout.activity_contacts);

        myPackageName = getPackageName();
        detailsclass=new DeviceDetailsClass(this);
        default_application=(RelativeLayout)findViewById(R.id.default_application);
        default_application.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new
                        AlertDialog.Builder(Contacts.this);
                builder.setMessage(
                        "Way2Inbox is not set as your default messaging app. Do you want to set it default?")
                        .setCancelable(false)
                        .setTitle("Alert!")
                        .setNegativeButton("No",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        default_application.setVisibility(View.GONE);

                                    }
                                }).setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            @TargetApi(19)
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                default_application.setVisibility(View.GONE);
                                Intent intent = new Intent(
                                        Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);

                                intent.putExtra(
                                        Telephony.Sms.Intents.EXTRA_PACKAGE_NAME,
                                        getPackageName());
                               // PrintMsg.setLogerror(ComposeSmsActivity.this,"Package name is :"+getPackageName());
                                startActivity(intent);

                            }
                        });
                builder.show();
            }
        });

        initList();
        contactslist = (ListView) findViewById(R.id.contactListView);
        contactslist.setOnItemClickListener(this);
        aAdpt = new ContactsAdapter(planetsList, this);
        contactslist.setAdapter(aAdpt);
        contactslist.setTextFilterEnabled(true);
        Chat_Send = (RelativeLayout) findViewById(R.id.Chat_Send);
        Chat_Send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                number = search.getText().toString();
if(number.length()>9) {
    System.out.println("thi si no" + number);
    Intent i = new Intent(Contacts.this, ComposeSmsActivity.class);
    i.putExtra("MobileName", "NONE");
    i.putExtra("MobileNo", number);
    startActivity(i);
    finish();
}else{
    PrintMsg.SetToast(Contacts.this,getResources().getString(R.string.noNumbertosend),1);
}

            }
        });
        back=(RelativeLayout)findViewById(R.id.back);
        back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Contacts.this, Messages.class));
                finish();
            }
        });
        search = (EditText) findViewById(R.id.search_box);
        search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (count < before) {
                    // We're deleting char so we need to reset the adapter data
                    aAdpt.resetData();

                }
                if(count==0){
             check_default();
                }else{
                    default_application.setVisibility(View.GONE);
                }
                aAdpt.getFilter().filter(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
    }

    private void initList() {
        try {
            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            String[] projection = new String[] { ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER };
            String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER
                    + " = '1'";
            String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
                    + " COLLATE LOCALIZED DESC";
            if (selection.length() > 1) {
                contacts = getContentResolver().query(uri, projection,
                        selection, null, sortOrder);
                while (contacts.moveToNext()) {
                    planetsList.add(new phonecontacts_model(contacts
                            .getString(1), contacts.getString(2)));
                    System.out.println(contacts.getString(1) + "   "
                            + contacts.getString(2));
                }

            }
        } catch (Exception e) {

        }
    }
    @Override
    public void onResume(){
        super.onResume();
        check_default();
    }
    public void check_default(){
        if(detailsclass.getversion()) {
            if (!detailsclass.getdefaultpackage(myPackageName)) {
                default_application.setVisibility(View.VISIBLE);
            }else{
                default_application.setVisibility(View.GONE);
            }
        }
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        TextView name = (TextView) view.findViewById(R.id.contact_name);
        TextView phoneno = (TextView) view.findViewById(R.id.contact_number);
        String phone = phoneno.getText().toString();
        // phonecontacts_model model=planetsList.get(position);
        // String name= model.getName();
        // String phoneno=model.getPhoneno();
        if (phone.length() >= 10) {
            phone = phone.replaceAll(" ", "");
            phone = phone.substring(phone.length() - 10, phone.length());

        Intent i = new Intent(this, ComposeSmsActivity.class);
        i.putExtra("MobileName", name.getText().toString());
        i.putExtra("MobileNo", phone);
        startActivity(i);
        finish();

    }else{
        PrintMsg.SetToast(Contacts.this,getResources().getString(R.string.noNumbertosend),1);
    }
    }
}
